import { useMemoizedFn } from 'ahooks';
import { Spin } from 'antd';
import { isNil } from 'lodash';
import { memo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { rootRouter } from '.';
import { updateDynamicRouter, useAppDispatch, useAppSelector } from '../store';
import { HOME_URL } from './AuthRouter';
import { RouteItem } from './Type';

const CreateRouter = () => {
    const navigate = useNavigate();
    const info = useAppSelector((state) => state.user.info);
    const dispatch = useAppDispatch();

    const createRouter = useMemoizedFn(async () => {
        if (info) {
            const getRouterList = (routers: RouteItem[]) => {
                const relut: string[] = [];
                routers.forEach((item) => {
                    if (item.children) {
                        relut.push(...getRouterList(item.children));
                    } else {
                        if (isNil(item.path)) return;
                        relut.push(item.path);
                    }
                });
                return relut;
            };

            const list = getRouterList(rootRouter);
            console.log(list);

            dispatch(updateDynamicRouter(list));

            navigate(HOME_URL);
        }
    });

    useEffect(() => {
        createRouter();
    }, [createRouter]);

    return (
        <Spin
            size="large"
            style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                height: '100%',
            }}
        />
    );
};

export default memo(CreateRouter);
